package com.securityjava.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

/**
 * 获取用户相关信息
 * @author charlie
 *
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
	private Logger log = LoggerFactory.getLogger(UserDetailServiceImpl.class);



	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

		String password=getPwdFromDB(userName);


		Collection<GrantedAuthority> authList = getAuthorities(userName);
		org.springframework.security.core.userdetails.User securityUser =
				new org.springframework.security.core.userdetails.User
						(
								userName,
								password,
								true,
								true,
								true,
								true,
								authList
						);

		return securityUser;
	}
	private  String getPwdFromDB(String userName) throws UsernameNotFoundException {
		String password="admin";
		if(userName.equals("admin")) {
			password="admin";
		}
		else if(userName.equals("user")) {
			password="user";
		}
		else {
			throw new UsernameNotFoundException("登录用户：" + userName + " 不存在");
		}
		BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
		password = bCryptPasswordEncoder.encode(password);
		return password;

	}
	/**
	 * 获取用户的角色权限,为了降低实验的难度，这里去掉了根据用户名获取角色的步骤
	 *  * @param
	 *  * @return
	 *  */
	private Collection<GrantedAuthority> getAuthorities(String userName){
		List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
		if(userName.equals("admin")){
			authList.add(new SimpleGrantedAuthority("ROLE_USER"));
			authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
		}
		else{
			authList.add(new SimpleGrantedAuthority("ROLE_USER"));
		}
		return authList;
	}

}

